package com.runen.wnhz.runen.ui.fragment.minem;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.CancleOrderBean;
import com.runen.wnhz.runen.bean.CourseDetailCommentBean;
import com.runen.wnhz.runen.bean.PingLunBean;
import com.runen.wnhz.runen.common.dialog.BaseDialog;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.NetStateUtils;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.CourseCommentRecyclerAdapter;
import com.runen.wnhz.runen.ui.fragment.BaseFragment;
import com.runen.wnhz.runen.widget.TitleBuilder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.simple.eventbus.Subscriber;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018-04-11.
 */

public class MessageFragment extends BaseFragment implements View.OnClickListener {

    private int currentPage = 0;
    private boolean hasNextPage = false;
    private int totalPage = 0;
    private boolean isRefresh = false;
    private boolean isloadMore = false;
    RecyclerView rvMessage;
    SmartRefreshLayout smartRefreshLayout;
    TextView text_evaluate;
    public BaseDialog commentDialog;
    private View commentView;
    private EditText edit_comment_content;
    private Button btn_commitComment;
    private List<CourseDetailCommentBean.DataBean.ListBean> listBean;
    private String lid;
    private CourseCommentRecyclerAdapter adapter;
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (edit_comment_content.getText().toString().length() >= 1) {
                btn_commitComment.setBackground(getResources().getDrawable(R.drawable.comment_button_can_shape));
                btn_commitComment.setEnabled(true);
            } else {
                btn_commitComment.setBackground(getResources().getDrawable(R.drawable.comment_button_no_cancle_shape));
                btn_commitComment.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

    public static MessageFragment newInstance(String lid) {
        MessageFragment fragment = new MessageFragment();
        Bundle bundle = new Bundle();
        bundle.putString("lid", lid);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {

    }

    @Subscriber
    public void onReceivePingLunBean(PingLunBean pingLunBean){
        if(pingLunBean != null){
           isRefresh = true;
           int tempCurrentPage = 0;
           getCourseComment(String.valueOf(tempCurrentPage));
        }
    }

    @Override
    protected int getLayoutView() {
        return R.layout.message_fragment_layout;
    }

    @Override
    public void initUiAndListener(View view) {
        rvMessage = view.findViewById(R.id.rv_message);
        rvMessage.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
        smartRefreshLayout = view.findViewById(R.id.smart_refresh_layout);
        text_evaluate = view.findViewById(R.id.text_evaluate);
        commentView = View.inflate(getActivity(), R.layout.comment_layout, null);
        edit_comment_content = commentView.findViewById(R.id.edit_comment_content);
        btn_commitComment = commentView.findViewById(R.id.btn_commitComment);
        commentDialog = new BaseDialog.Builder(getActivity()).setContentView(commentView).fullWidth().fromBottom(true).create();
        listBean = new ArrayList<>();

        text_evaluate.setOnClickListener(this);
        btn_commitComment.setOnClickListener(this);
        edit_comment_content.addTextChangedListener(textWatcher);
        smartRefreshLayout.setEnableAutoLoadMore(false);
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if(NetStateUtils.isNetworkAvalible(getActivity())){
                    if(hasNextPage){
                        int tempCurrentPage = currentPage + 1;
                        isloadMore = true;
                        getCourseComment(String.valueOf(tempCurrentPage));
                    }else{
                        ToastUtil.showToast("暂无更多数据");
                        smartRefreshLayout.finishLoadMore(true);
                    }
                }else{
                    ToastUtil.showToast("当前暂无网络");
                    smartRefreshLayout.finishLoadMore(false);
                }

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if(NetStateUtils.isNetworkAvalible(getActivity())){
                    int tempCurrentPage = 0;
                    isRefresh = true;
                    getCourseComment(String.valueOf(tempCurrentPage));
                }else{
                    ToastUtil.showToast("当前暂无网络");
                    smartRefreshLayout.finishRefresh(false);
                }
            }
        });

    }

    private void refreshOrLoadMoreFailure(){
        if(isRefresh){
            smartRefreshLayout.finishRefresh(false);
            isRefresh = false;
        }
        if(isloadMore){
            smartRefreshLayout.finishLoadMore(false);
            isloadMore = false;
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setUserVisibleHint(true);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            if(getActivity() != null) {
                getCourseComment(String.valueOf(currentPage));
            }
        }
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        setToolBarVisible(View.GONE);
    }

    @Override
    public void showLoadding() {

    }

    @Override
    public void dimissLoding() {

    }

    @Override
    public void showErrorMessage(String msg) {

    }

    @Override
    public void onTitleButtonClicked(TitleBuilder.TitleButton clicked) {

    }


    private void getCourseComment(String page) {
        if(getArguments() != null) {
            lid = getArguments().getString("lid");
        }
        ACacheUtlis cacheUtlis = ACacheUtlis.getInstance();
        if (cacheUtlis != null) {
            UserBean reqeustUser = cacheUtlis.getReqeustUser(getActivity());
            if (reqeustUser != null) {
                String token = reqeustUser.getToken();
                if (lid != null && token != null) {
                    FormBody formBody = new FormBody.Builder().add("lid", lid).add("token", token).add("page", page).build();
                    Request request = new Request.Builder().url(NetUtils.COURSE_DETAIL_TALK).post(formBody).build();
                    Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
                    newCall.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.showToast("数据请求失败");
                                    refreshOrLoadMoreFailure();
                                }
                            });
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            try {
                                handleCourseDetailData(response);
                            } catch (IOException e) {
                                e.printStackTrace();
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtil.showToast("请求评论数据异常");
                                        refreshOrLoadMoreFailure();
                                    }
                                });
                            }
                        }
                    });
                }
            }
        }
    }

    private void handleCourseDetailData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                final String json = responseBody.string();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CourseDetailCommentBean courseDetailCommentBean = new Gson().fromJson(json, CourseDetailCommentBean.class);
                        System.out.println("courseDetailCommentBean == " + courseDetailCommentBean.toString());
                        if ("1".equals(courseDetailCommentBean.getRe())) {
                            CourseDetailCommentBean.DataBean dataBean = courseDetailCommentBean.getData();
                            String isPage = dataBean.getIs_page();
                            if ("1".equals(isPage)) {
                                hasNextPage = true;
                            } else {
                                hasNextPage = false;
                            }
                            totalPage = Integer.parseInt(dataBean.getSum_page());
                            currentPage = Integer.parseInt(dataBean.getPage());
                            List<CourseDetailCommentBean.DataBean.ListBean> list = dataBean.getList();
                            if (isRefresh) {
                                if (list.size() != 0) {
                                    currentPage = 0;
                                }
                                if (listBean.size() != 0) {
                                    listBean.clear();
                                }
                                listBean.addAll(list);
                                if (adapter == null) {
                                    adapter = new CourseCommentRecyclerAdapter(getActivity(), listBean,lid);
                                    adapter.setMessageFragment(MessageFragment.this);
                                    rvMessage.setAdapter(adapter);
                                } else {
                                    adapter.notifyDataSetChanged();
                                }
                                isRefresh = false;
                                smartRefreshLayout.finishRefresh(true);
                                return;
                            }
                            if (isloadMore) {
                                if (list.size() != 0) {
                                    currentPage = currentPage + 1;
                                }
                                listBean.addAll(list);
                                if (adapter == null) {
                                    adapter = new CourseCommentRecyclerAdapter(getActivity(), listBean,lid);
                                    adapter.setMessageFragment(MessageFragment.this);
                                    rvMessage.setAdapter(adapter);
                                } else {
                                    adapter.notifyDataSetChanged();
                                }
                                isloadMore = false;
                                smartRefreshLayout.finishLoadMore(true);
                                return;
                            }
                            currentPage = 0;
                            if(listBean.size() != 0){
                                listBean.clear();
                            }
                            listBean.addAll(dataBean.getList());
                            adapter = new CourseCommentRecyclerAdapter(getActivity(), listBean,lid);
                            adapter.setMessageFragment(MessageFragment.this);
                            rvMessage.setAdapter(adapter);
                        } else if ("0".equals(courseDetailCommentBean.getRe())) {
                            ToastUtil.showToast(courseDetailCommentBean.getInfo());
                            refreshOrLoadMoreFailure();
                        } else if ("-1".equals(courseDetailCommentBean.getRe())) {
                            ToastUtil.showToast(courseDetailCommentBean.getInfo());
                            startActivity(new Intent(getActivity(), LoginForPersonalActivity.class));
                            refreshOrLoadMoreFailure();
                        }

                    }
                });
            }
        }
    }

    private void commitComment() {
        ACacheUtlis cacheUtlis = ACacheUtlis.getInstance();
        if (cacheUtlis != null) {
            UserBean reqeustUser = cacheUtlis.getReqeustUser(getActivity());
            if (reqeustUser != null) {
                String token = reqeustUser.getToken();
                Bundle arguments = getArguments();
                if (arguments != null) {
                    String lid = arguments.getString("lid");
                    if (lid != null) {
                        FormBody formBody = new FormBody.Builder().add("token", token).add("lid", lid).add("content", edit_comment_content.getText().toString()).build();
                        Request request = new Request.Builder().url(NetUtils.COMMIT_COMMENT).post(formBody).build();
                        Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
                        newCall.enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtil.showToast("评论提交失败");
                                    }
                                });
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                try {
                                    handleCommitCommentData(response);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    ToastUtil.showToast("评论提交出现异常");
                                }
                            }
                        });
                    }
                }

            }
        }

    }

    private void handleCommitCommentData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                final String json = responseBody.string();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CancleOrderBean cancleOrderBean = new Gson().fromJson(json, CancleOrderBean.class);
                        if ("1".equals(cancleOrderBean.getRe())) {
                            ToastUtil.showToast(cancleOrderBean.getInfo());
                            edit_comment_content.setText("");
                            getCourseComment("0");
                        } else if ("0".equals(cancleOrderBean.getRe())) {
                            ToastUtil.showToast(cancleOrderBean.getInfo());
                        } else if ("-1".equals(cancleOrderBean.getRe())) {
                            ToastUtil.showToast(cancleOrderBean.getInfo());
                            startActivity(new Intent(getActivity(), LoginForPersonalActivity.class));
                        }
                    }
                });

            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.text_evaluate:
                commentDialog.show();
                break;
            case R.id.btn_commitComment:
                commitComment();
                if (commentDialog != null && commentDialog.isShowing()) {
                    commentDialog.dismiss();
                }
                break;
        }
    }
}
